import { createRouter, createWebHistory } from 'vue-router'
import BasicLayout from '@/layouts/BasicLayout.vue'
// 主页
import HomePage from '@/views/HomePage.vue'
// 用户
import UserLoginPage from '@/views/user/UserLoginPage.vue'
import UserRegisterPage from '@/views/user/UserRegisterPage.vue'
// 管理员
import UserManagePage from '@/views/admin/UserManagePage.vue'
import UserManagementPage from '@/views/user/UserManagementPage.vue'

import { useLoginUserStore } from '@/stores/useLoginUserStore'
import { storeToRefs } from 'pinia'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: '主页',
      component: HomePage,
      meta: {
        layout: BasicLayout,
        requiresAuth: true,
        showInNav: true,
      },
    },
    {
      path: '/user/login',
      name: '用户登录',
      component: UserLoginPage,
      meta: {
        noAuth: true,
        showInNav: false,
      },
    },
    {
      path: '/user/register',
      name: '用户注册',
      component: UserRegisterPage,
      meta: {
        noAuth: true,
        showInNav: false,
      },
    },
    {
      path: '/admin/userManage',
      name: '用户管理',
      component: UserManagePage,
      meta: {
        layout: BasicLayout,
        requiresAuth: true,
        showInNav: true,
      },
    },
    {
      path: '/user-management',
      name: '用户管理',
      component: UserManagementPage,
      meta: {
        layout: BasicLayout,
        requiresAuth: true,
        showInNav: true,
      },
    },
  ],
})

router.beforeEach(async (to) => {
  const loginUserStore = useLoginUserStore()
  const { loginUser } = storeToRefs(loginUserStore)

  // 如果本地有存储的用户信息，尝试获取最新的用户信息
  if (localStorage.getItem('loginUser')) {
    try {
      await loginUserStore.fetchLoginUser()
    } catch (error) {
      console.error('获取用户信息失败:', error)
    }
  }

  if (to.meta.requiresAuth && loginUser.value.userName === '未登录') {
    return {
      path: '/user/login',
      // query: { redirect: to.fullPath },
    }
  }

  if (to.meta.noAuth && loginUser.value.userName !== '未登录') {
    return { path: '/' }
  }

  return true
})

export default router
